//
//  HomeRefreshControl.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/6/9.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class HomeRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        
        //初始化
        setupUI()
    }
    
    func setupUI() -> Void {
        
        //1.添加子控件
        addSubview(refreshView)
        //2.布局子控件
        addConstraint(NSLayoutConstraint.init(item: refreshView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint.init(item: refreshView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0));
        addConstraint(NSLayoutConstraint.init(item: refreshView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 170))
        addConstraint(NSLayoutConstraint.init(item: refreshView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 60))
        
        /*
          当用户下拉到一定程度的时候,要旋转我们的箭头
          当用户上推到一定程度的时候,我们要旋转箭头
          当用户触发刷新的方法时候,我们要显示刷新界面
         
         利用KVO来监听事件
         */
        //监听frame的新值
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil)
    }
    
    
    /// 定义变量记录箭头是否需要旋转
    private var roationArrowFlag = false;
    
    /// 定义变量记录是否正在执行圈圈动画
    private var loadingViewFlag = false;
    /// 使用KVO监听属性 回调方法
    ///
    /// - Parameters:
    ///   - keyPath: <#keyPath description#>
    ///   - object: <#object description#>
    ///   - change: <#change description#>
    ///   - context: <#context description#>

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //print("-=====",NSStringFromCGRect(frame))
        if frame.origin.y >= 0 {
            return
        }
        //open var isRefreshing: Bool { get }
        //系统自带属性,当你触发刷新的时候 这个属性自动被系统赋值 true  没有则是 false
        if isRefreshing && !loadingViewFlag {
            loadingViewFlag = true;
            //1.显示圈圈,并且开起旋转
            refreshView.startAnnimation()
            return
        }
        if frame.origin.y >= -50 && roationArrowFlag{
            roationArrowFlag = false
            refreshView.rotaionArrowicon(flag: roationArrowFlag)
            
        }else if frame.origin.y < -50 && !roationArrowFlag{
            roationArrowFlag = true
            refreshView.rotaionArrowicon(flag: roationArrowFlag)
        }
    }
    
    /// 重写系统的endRefreshing()方法 系统结束刷新
    override func endRefreshing() {
        super.endRefreshing()
        //1.停止转圈动画 并且显示View
        refreshView.stopAnnimation()
        
        //2.复位标签圈圈动画的标记
        loadingViewFlag = false
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    // MARK: -- 懒加载
    
    private lazy var refreshView:HomeRefreshView = HomeRefreshView.refreshView()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class HomeRefreshView: UIView {
    
    @IBOutlet weak var loadImageView: UIImageView!
    
    @IBOutlet weak var TopView: UIView!
    
    @IBOutlet weak var arrowIcon: UIImageView!
    
    /// 旋转箭头
    func rotaionArrowicon(flag: Bool) -> Void {
        var angle = Double.pi
        angle += flag ? -0.01 : 0.01
        UIView.animate(withDuration: 0.2) {
            //swift M_PI -> Double.pi or .pi
            self.arrowIcon.transform = self.arrowIcon.transform.rotated(by: CGFloat(angle))
        }
    }
    
    /// 开始动画
    func startAnnimation() -> Void {
        TopView.isHidden = true
        //1.创建动画
        let animation = CABasicAnimation.init(keyPath: "transform.rotation")//旋转动画
        //2.设置动画的属性
        animation.toValue = 2 * Double.pi //动画的停止的值
        animation.duration = 1.0//设置动画完成一边的时间
        animation.repeatCount = MAXFLOAT //动画的重复次数
        //当视图的隐藏的时候  动画默认停止  我们要设置属性 让动画不会停止
        animation.isRemovedOnCompletion = false  //默认是true
        //3.添加动画
        loadImageView.layer.add(animation, forKey: nil)
    }
    
    /// 停止动画
    func stopAnnimation() -> Void {
        TopView.isHidden = false;
        loadImageView.layer.removeAllAnimations()
    }
    
    class func refreshView() -> HomeRefreshView {
        let tt = Bundle.main.loadNibNamed("HomeRefreshView", owner: nil, options: nil)?.first as! HomeRefreshView
        tt.translatesAutoresizingMaskIntoConstraints = false
        
        return tt
    }
}
